<template>
  <div class="user-container">
    <el-container>
      <el-aside width="200px" class="dept-tree-aside">
        <el-card style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>部门列表</span>
            </div>
          </template>
          <el-tree
              :data="deptTree"
              :props="defaultProps"
              @node-click="handleNodeClick"
              default-expand-all
              highlight-current
              node-key="id"
          />
        </el-card>
      </el-aside>
      <el-main class="user-list-main">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户管理</span>
              <el-button type="primary" @click="handleAdd" v-permission="'system:user:add'">新增用户</el-button>
            </div>
          </template>

          <!-- 搜索表单 -->
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable/>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" style="width: 120px" placeholder="请选择状态" clearable>
                <el-option label="启用" :value="1"/>
                <el-option label="禁用" :value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="userList" style="width: 100%" border>
            <el-table-column type="index" label="序号" width="60" fixed/>
            <el-table-column prop="username" label="用户名" align="center"/>
            <el-table-column prop="nickname" label="昵称" align="center"/>
            <el-table-column prop="email" label="邮箱" align="center"/>
            <el-table-column prop="phone" label="手机号" align="center"/>
            <el-table-column prop="status" label="状态" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)" v-permission="'system:user:edit'">编辑
                </el-button>
                <el-button type="primary" link @click="handleDelete(row)" v-permission="'system:user:delete'">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :small="false"
              :disabled="false"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </el-card>
      </el-main>
    </el-container>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {ElMessage, ElMessageBox, type FormInstance} from 'element-plus'
import {getUserPageByDept, addUser, updateUser, deleteUser} from '@/api/user'
import {getDeptList} from '@/api/dept'

interface SysUser {
  id?: number;
  username: string;
  password?: string;
  nickname: string;
  email: string;
  phone: string;
  status: number;
  createTime?: string;
  updateTime?: string;
}

interface DeptTreeItem {
  id: number;
  name: string;
  children?: DeptTreeItem[];
}

const userList = ref<SysUser[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

const form = ref<SysUser>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  status: 1
})

const rules = {
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}],
  email: [{type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}],
  phone: [{pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change']}]
}

const deptTree = ref<DeptTreeItem[]>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}
const selectedDeptId = ref<number | null>(null)

const searchForm = ref({
  username: '',
  phone: '',
  status: null
})

const fetchDeptTree = async () => {
  const res = await getDeptList()
  if (res.code === 200) {
    const rootDept: DeptTreeItem = {
      id: 0,
      name: '所有部门',
      children: res.data
    }
    deptTree.value = [rootDept]
  }
}

const fetchUserList = async () => {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    deptId: selectedDeptId.value === 0 ? null : selectedDeptId.value,
    username: searchForm.value.username,
    phone: searchForm.value.phone,
    status: searchForm.value.status
  }
  const res = await getUserPageByDept(params)
  if (res.code === 200) {
    userList.value = res.data.records
    total.value = res.data.total
  }
}

const handleNodeClick = (data: DeptTreeItem) => {
  selectedDeptId.value = data.id
  pageNum.value = 1
  fetchUserList()
}

const handleSearch = () => {
  pageNum.value = 1
  fetchUserList()
}

const resetSearch = () => {
  searchForm.value = {
    username: '',
    phone: '',
    status: null
  }
  pageNum.value = 1
  fetchUserList()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val: number) => {
  pageNum.value = val
  fetchUserList()
}

const resetForm = () => {
  form.value = {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    status: 1
  }
  formRef.value?.resetFields()
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: SysUser) => {
  dialogType.value = 'edit'
  form.value = {...row}
  dialogVisible.value = true
}

const handleDelete = (row: SysUser) => {
  ElMessageBox.confirm('确认要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (row.id === undefined) return ElMessage.error('用户ID不存在')
    const res = await deleteUser(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await fetchUserList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const api = dialogType.value === 'add' ? addUser : updateUser
      const res = await api(form.value)
      if (res.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
        dialogVisible.value = false
        await fetchUserList()
      } else {
        ElMessage.error(res.msg || (dialogType.value === 'add' ? '新增失败' : '编辑失败'))
      }
    }
  })
}

onMounted(async () => {
  await fetchDeptTree()
  await fetchUserList()
})

watch(selectedDeptId, async () => {
  await fetchUserList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  height: 100%; /* 确保容器有高度 */
}

.el-container {
  height: calc(100vh - 100px); /* 减去顶部导航等高度 */
  align-items: flex-start; /* 确保子元素顶部对齐 */
}

.dept-tree-aside {
  margin-right: 20px;
}

.dept-tree-aside .el-card,
.user-list-main .el-card {
  height: 100%; /* 让卡片填充可用高度 */
}

/* 统一 el-card__header 的样式，确保头部高度和内容垂直居中 */
.dept-tree-aside .el-card .el-card__header,
.user-list-main .el-card .el-card__header {
  height: 52px; /* 固定头部高度，例如：32px (内容) + 10px*2 (padding) */
  display: flex;
  align-items: center;
  padding: 0 20px; /* 移除垂直方向的 padding，让内容高度撑开 */
  box-sizing: border-box;
}

/* .card-header 不再控制高度和行高，只用于内部布局 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%; /* 确保它占据 el-card__header 的全部宽度 */
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
